import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {

        int n = nums.length;
        Arrays.sort(nums);

        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int target = -nums[i] - nums[j];
                int index = binary(nums, j + 1, n - 1, target);
                if (index != -1) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[index]);
                    ret.add(list);
                }

                //跳过相同元素
                int num = nums[j];
                while (j < n && nums[j] == num) {
                    j++;
                }
                j--;
            }

            //跳过相同的元素
            int num = nums[i];
            while (i < n && nums[i] == num) {
                i++;
            }
            i--;
        }

        return ret;
    }

    //二分查找符合条件的元素
    public static int binary(int[] nums, int left, int right, int target) {

        if (left >= nums.length) {
            return -1;
        }

        if (nums[left] == target) {
            return left;
        } else if (nums[right] == target) {
            return right;
        }

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] == target) {
                return mid;
            } else {
                left = mid + 1;
            }
        }

        return -1;
    }
}